import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/cate',
    name: 'cate',
    component: () => import('@views/Cate'),
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/cart',
    name: 'cart',
    component: () => import('@views/Cart'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('@views/User'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/itemLists',
    name: 'itemLists',
    component: () => import('@views/ItemLists'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/detail/:itemId',
    name: 'detail',
    component: () => import('@views/Detail'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/currentOrder',
    name: 'currentOrder',
    component: () => import('@views/CurrentOrder'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/contactList',
    name: 'contactList',
    component: () => import('@views/ContactList'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/contactAdd',
    name: 'contactAdd',
    component: () => import('@views/ContactAdd'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/contactEdit',
    name: 'contactEdit',
    component: () => import('@views/ContactEdit'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@views/Search'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/searchResult',
    name: 'searchResult',
    component: () => import('@views/SearchResult'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@views/Login'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 判断是否需要登录
  if (to.meta.needLogin) {
    // 需要登录 access_token auth_token
    const authToken = localStorage.getItem('auth_token')
    if (authToken) {
      // 登录了
      next()
    } else {
      // 没有登录
      next({
        path: '/login',
        query: {
          from: to.path
        }
      })
    }
  } else {
    next()
  }
})

export default router
